from fastapi import APIRouter, HTTPException
import json
import os

router = APIRouter()


def _locate_required_params_file() -> str:
    candidate_paths = [
        os.path.join("/app", "config", "required_params.json"),  # 容器优先
        os.path.join(os.getcwd(), "config", "required_params.json"),
        os.path.join(os.path.dirname(__file__), "../../../../config/required_params.json"),
    ]
    for p in candidate_paths:
        if os.path.isfile(p):
            return p
    return candidate_paths[-1]


@router.get("/system-settings")
def get_system_settings():
    try:
        path = _locate_required_params_file()
        if not os.path.isfile(path):
            # 内置默认
            return {
                "requiredFields": ["projectName", "projectType", "uiFramework"],
                "defaults": {
                    "language": "typescript",
                    "buildTool": "vite",
                    "targetPlatform": "web"
                },
                "requiredBaseComponents": {
                    "react": ["react", "react-dom"],
                    "vue": ["vue"]
                },
                "featureToggles": {"persistConfig": False}
            }
        with open(path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
